package com.jcfk.system.service;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.jcfk.common.web.domain.LoginInfo;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.domain.dto.*;
import com.jcfk.system.domain.po.*;
import com.jcfk.system.domain.query.OaKeyworkWeeklyActualQuery;
import com.jcfk.system.domain.query.OaKeyworkWeeklyPlanQuery;
import com.jcfk.system.domain.query.OaKeyworkWeeklyQuery;
import com.jcfk.system.dao.OaKeyworkWeeklyDao;
import com.jcfk.system.dao.OaKeyworkWeeklyDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.*;

import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 周报计划事项
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-04-02
 */
@Service
public class OaKeyworkWeeklyService extends BaseService<OaKeyworkWeeklyDao, OaKeyworkWeekly> {


    @Autowired
    private OaKeyworkWeeklyPlanService oaKeyworkWeeklyPlanService;

    @Autowired
    private OaKeyworkWeeklyActualService oaKeyworkWeeklyActualService;

    @Autowired
    private SysAnnexesFileService sysAnnexesFileService;

    @Autowired
    private OaKeyworkTaskService oaKeyworkTaskService;

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Autowired
    private RefUserOrganizationMappingService refUserOrganizationMappingService;

    /**
     * OaKeyworkWeekly分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<OaKeyworkWeeklyDTO> queryByPage(DataPage<OaKeyworkWeeklyDTO> page, OaKeyworkWeeklyQuery query) {
        List<OrderItem> orders = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("work_year");
        orders.add(orderItem);
        page.setOrders(orders);

        OrderItem item = new OrderItem();
        item.setAsc(false);
        item.setColumn("work_week");
        orders.add(item);

        page.setOrders(orders);

        // 分页查询
        query.setCreatedUserName(StringUtils.isEmpty(query.getCreatedUserName()) ? query.getCreatedUserName() : "%" + query.getCreatedUserName() + "%");
        query.setWeeklyDetail(StringUtils.isEmpty(query.getWeeklyDetail()) ? query.getWeeklyDetail() : "%" + query.getWeeklyDetail() + "%");


        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();


        if (query.getCreatedUserId() == null) {
            // 超级管理员
            if (!"superadmin".equals(loginInfo.getUserType())) {
                List<String> userids = getuserIds();
                query.setUserIds(userids);
                if (userids.size() == 0) {
                    return page;
                }
            }

        }
        page = this.baseMapper.queryByPage(page, query);

        return page;
    }

    public List<String> getuserIds() {
        List<String> userids = new ArrayList<>();
        List<SysOrganizationDTO> sysOrganizationDTOS = LoginUserInfoUtils.getUserOrgans();
        List<String> allids = sysOrganizationDTOS.stream().map(SysOrganizationDTO::getAllId).collect(Collectors.toList());
        if (allids.size() == 0) return userids;

        QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
        sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getDeleted, 0);
        if (allids.size() > 0) {
            sysOrganizationQueryWrapper.lambda().and(wapper -> {
                for (String id : allids) {
                    wapper.or().likeRight(SysOrganization::getAllId, id);
                }
            });
        }
        List<SysOrganization> list = sysOrganizationService.list(sysOrganizationQueryWrapper);
        if (list.size() == 0) return userids;

        List<String> orgids = list.stream().map(SysOrganization::getId).collect(Collectors.toList());

        QueryWrapper<RefUserOrganizationMapping> refUserOrganizationMappingQueryWrapper = new QueryWrapper<>();
        refUserOrganizationMappingQueryWrapper.lambda().in(RefUserOrganizationMapping::getOrganizationId, orgids);
        List<RefUserOrganizationMapping> users = refUserOrganizationMappingService.list(refUserOrganizationMappingQueryWrapper);
        userids = users.stream().map(RefUserOrganizationMapping::getUserId).collect(Collectors.toList());
        return userids;

    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<OaKeyworkWeeklyDTO>
     */
    public List<OaKeyworkWeeklyDTO> getList(OaKeyworkWeeklyQuery query) {
        // 查询条件
        QueryWrapper<OaKeyworkWeekly> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getWorkWeek()), OaKeyworkWeekly::getWorkWeek, query.getWorkWeek());
        qw.lambda().eq(!"".equals(query.getWorkYear()), OaKeyworkWeekly::getWorkYear, query.getWorkYear());
        qw.lambda().like(!StrUtil.isEmpty(query.getWeeklyDetail()), OaKeyworkWeekly::getWeeklyDetail, query.getWeeklyDetail());
        qw.lambda().ge(!StrUtil.isEmpty(query.getStartTimeStart()), OaKeyworkWeekly::getStartTime, query.getStartTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getStartTimeEnd()), OaKeyworkWeekly::getStartTime, query.getStartTimeEnd());
        qw.lambda().ge(!StrUtil.isEmpty(query.getEndTimeStart()), OaKeyworkWeekly::getEndTime, query.getEndTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getEndTimeEnd()), OaKeyworkWeekly::getEndTime, query.getEndTimeEnd());
        qw.lambda().eq(!StrUtil.isEmpty(query.getCreatedUserId()), OaKeyworkWeekly::getCreatedUserId, query.getCreatedUserId());
        // 查询数据
        List<OaKeyworkWeekly> list = super.list(qw);

        return convertList(list, OaKeyworkWeeklyDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<OaKeyworkWeeklyDTO>
     */
    public List<OaKeyworkWeeklyPlanDTO> getDetails(OaKeyworkWeeklyQuery query) {
        // 查询条件
        QueryWrapper<OaKeyworkWeeklyPlan> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), OaKeyworkWeeklyPlan::getWeeklyId, query.getId());

        // 查询数据
        List<OaKeyworkWeeklyPlan> list = oaKeyworkWeeklyPlanService.list(qw);

        return convertList(list, OaKeyworkWeeklyPlanDTO.class);
    }


    /**
     * 判断OaKeyworkWeekly是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(OaKeyworkWeeklyDTO dto) {
        QueryWrapper<OaKeyworkWeekly> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.lambda().eq(OaKeyworkWeekly::getCreatedUserId, SecurityUtils.getUserId());
        queryWrapper.lambda().eq(OaKeyworkWeekly::getWorkWeek, dto.getWorkWeek());
        queryWrapper.lambda().eq(OaKeyworkWeekly::getWorkYear, dto.getWorkYear());

        if (!StrUtil.isEmpty(dto.getId())) {
            queryWrapper.lambda().ne(OaKeyworkWeekly::getId, dto.getId());
        }

        long count = this.baseMapper.selectCount(queryWrapper);

        if (count > 0) {
            return RetResult.fail("您已经存该周的周报");
        }

        return RetResult.ok();
    }

    /**
     * 插入周报计划事项
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(OaKeyworkWeeklyDTO dto) {

        // 保存
        OaKeyworkWeekly item = new OaKeyworkWeekly();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (OaKeyworkWeeklyPlanDTO detail : dto.getPlans()) {
            detail.setWeeklyId(item.getId());
            detail.setWorkYear(item.getWorkYear());
            detail.setWorkWeek(item.getWorkWeek());
        }

        // 设置关联主键
        for (OaKeyworkWeeklyActualDTO detail : dto.getActuals()) {
            detail.setWeeklyId(item.getId());
            detail.setWorkYear(item.getWorkYear());
            detail.setWorkWeek(item.getWorkWeek());
        }

        // 保存明细表
        oaKeyworkWeeklyPlanService.saveBatch(dto.getPlans(), item.getId());
        oaKeyworkWeeklyActualService.saveBatch(dto.getActuals(), item.getId());

    }


    /**
     * 更新周报计划事项
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(OaKeyworkWeeklyDTO dto) {

        // 保存
        OaKeyworkWeekly item = new OaKeyworkWeekly();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (OaKeyworkWeeklyPlanDTO detail : dto.getPlans()) {
            detail.setWeeklyId(dto.getId());
            detail.setWorkYear(item.getWorkYear());
            detail.setWorkWeek(item.getWorkWeek());
        }
        // 设置关联主键
        for (OaKeyworkWeeklyActualDTO detail : dto.getActuals()) {
            detail.setWeeklyId(item.getId());
            detail.setWorkYear(item.getWorkYear());
            detail.setWorkWeek(item.getWorkWeek());
        }

        // 保存明细表
        oaKeyworkWeeklyPlanService.saveBatch(dto.getPlans(), item.getId());
        oaKeyworkWeeklyActualService.saveBatch(dto.getActuals(), item.getId());
    }


    /**
     * 根据批量主键删除周报计划事项(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(OaKeyworkWeeklyDTO dto) {
        OaKeyworkWeekly item = new OaKeyworkWeekly();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<OaKeyworkWeekly> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        this.update(item, queryWrapper);

        QueryWrapper<OaKeyworkWeeklyPlan> taskqueryWrapper = new QueryWrapper<>();
        taskqueryWrapper.lambda().in(OaKeyworkWeeklyPlan::getWeeklyId, dto.getIds());
        return oaKeyworkWeeklyPlanService.remove(taskqueryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(OaKeyworkWeekly item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setDeleted(0);
    }


    /**
     * 根据主键获取周报计划事项信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public OaKeyworkWeeklyDTO get(String id) {
        // 查询数据
        OaKeyworkWeekly item = this.baseMapper.selectById(id);
        OaKeyworkWeeklyDTO dto = new OaKeyworkWeeklyDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        // 本周计划
        OaKeyworkWeeklyPlanQuery query = new OaKeyworkWeeklyPlanQuery();
        query.setWeeklyId(id);
        List<OaKeyworkWeeklyPlanDTO> plan = oaKeyworkWeeklyPlanService.getList(query);
        dto.setPlans(plan);

        // 关联任务id
        List<String> taskids = new ArrayList<>();
        for (OaKeyworkWeeklyPlanDTO oaKeyworkWeeklyPlanDTO : plan) {
            if (oaKeyworkWeeklyPlanDTO.getType() == 2) taskids.add(oaKeyworkWeeklyPlanDTO.getTaskId());
        }

        // 周计划实际
        OaKeyworkWeeklyActualQuery actualQuery = new OaKeyworkWeeklyActualQuery();
        actualQuery.setWeeklyId(id);
        List<OaKeyworkWeeklyActualDTO> actualDTOS = oaKeyworkWeeklyActualService.getList(actualQuery);
        dto.setActuals(actualDTOS);
        for (OaKeyworkWeeklyActualDTO actualDTO : actualDTOS) {
            if (actualDTO.getType() == 2) taskids.add(actualDTO.getTaskId());
        }


        List<String> fileids = actualDTOS.stream().map(OaKeyworkWeeklyActualDTO::getId).collect(Collectors.toList());

        if (taskids.size() > 0) {
            QueryWrapper<OaKeyworkTask> taskqueryWrapper = new QueryWrapper<>();
            taskqueryWrapper.in("id", taskids);
            List<OaKeyworkTask> taskList = oaKeyworkTaskService.list(taskqueryWrapper);

            // 任务名称回显
            if (taskList.size() > 0) {
                Map<String, OaKeyworkTask> map = taskList.stream().collect(Collectors.toMap(OaKeyworkTask::getId, Function.identity()));
                for (OaKeyworkWeeklyPlanDTO dtoPlan : dto.getPlans()) {
                    if (dtoPlan.getType() == 2) {
                        dtoPlan.setTaskName(map.get(dtoPlan.getTaskId()) != null ? map.get(dtoPlan.getTaskId()).getTaskName() : "");
                    }
                }

                for (OaKeyworkWeeklyActualDTO actualDTO : actualDTOS) {
                    if (actualDTO.getType() == 2) {
                        actualDTO.setTaskName(map.get(actualDTO.getTaskId()) != null ? map.get(actualDTO.getTaskId()).getTaskName() : "");
                    }
                }
            }

        }


        // 附件
        if (fileids.size() > 0) {
            QueryWrapper<SysAnnexesFile> fileQueryWrapper = new QueryWrapper<>();
            fileQueryWrapper.lambda().eq(SysAnnexesFile::getOwnerType, "weekly_detail_file");
            fileQueryWrapper.lambda().in(SysAnnexesFile::getOwnerId, fileids);

            // 附件
            List<SysAnnexesFile> files = sysAnnexesFileService.list(fileQueryWrapper);


            List<SysAnnexesFileDTO> fileList = convertList(files, SysAnnexesFileDTO.class);
            // 将任务计划按照 taskid分组
            Map<String, SysAnnexesFileDTO> map = fileList.stream().collect(Collectors.toMap(SysAnnexesFileDTO::getOwnerId, Function.identity()));

            for (OaKeyworkWeeklyActualDTO actual : dto.getActuals()) {
                actual.setFile(map.get(actual.getId()));
            }
        }

        return dto;
    }

    public List<OaKeyworkWeeklyActualDTO> lastWeekPlans(OaKeyworkWeeklyDTO weeklyDTO) {
        // 查询条件
        QueryWrapper<OaKeyworkWeeklyActual> qw = new QueryWrapper<>();

        if (!StringUtils.isEmpty(weeklyDTO.getId())) {
            OaKeyworkWeekly item = this.baseMapper.selectById(weeklyDTO.getId());
            qw.lambda().eq(OaKeyworkWeeklyActual::getWorkWeek, item.getWorkWeek() - 1);
            qw.lambda().eq(OaKeyworkWeeklyActual::getWorkYear, item.getWorkYear());
            qw.lambda().eq(OaKeyworkWeeklyActual::getCreatedUserId, item.getCreatedUserId());
            qw.lambda().lt(OaKeyworkWeeklyActual::getCompletionDegree, 100);
        } else {
            Calendar calendar = Calendar.getInstance();

            if (weeklyDTO.getWorkYear() != null) {
                calendar.set(Calendar.YEAR, weeklyDTO.getWorkYear());
            }

            if (weeklyDTO.getWorkWeek() != null) {
                calendar.set(Calendar.WEEK_OF_YEAR, weeklyDTO.getWorkWeek());
            }

            calendar.add(Calendar.WEEK_OF_YEAR, -1); // 将日期设置为上一周
            int weekOfYear = calendar.get(Calendar.YEAR);
            int previousWeekNumber = calendar.get(Calendar.WEEK_OF_YEAR);

            qw.lambda().eq(OaKeyworkWeeklyActual::getWorkWeek, previousWeekNumber);
            qw.lambda().eq(OaKeyworkWeeklyActual::getWorkYear, weekOfYear);
            qw.lambda().eq(OaKeyworkWeeklyActual::getCreatedUserId, SecurityUtils.getUserId());
            qw.lambda().lt(OaKeyworkWeeklyActual::getCompletionDegree, 100);
        }


        qw.lambda().lt(OaKeyworkWeeklyActual::getCompletionDegree, 100);
        // 查询数据
        List<OaKeyworkWeeklyActual> list = oaKeyworkWeeklyActualService.list(qw);
        List<OaKeyworkWeeklyActualDTO> dtoList = convertList(list, OaKeyworkWeeklyActualDTO.class);

        // 关联任务id
        List<String> taskids = new ArrayList<>();
        for (OaKeyworkWeeklyActualDTO oaKeyworkWeeklyPlanDTO : dtoList) {
            if (oaKeyworkWeeklyPlanDTO.getType() == 2) taskids.add(oaKeyworkWeeklyPlanDTO.getTaskId());
        }


        if (taskids.size() > 0) {
            QueryWrapper<OaKeyworkTask> taskqueryWrapper = new QueryWrapper<>();
            taskqueryWrapper.in("id", taskids);
            List<OaKeyworkTask> taskList = oaKeyworkTaskService.list(taskqueryWrapper);

            // 任务名称回显
            if (taskList.size() > 0) {
                Map<String, OaKeyworkTask> map = taskList.stream().collect(Collectors.toMap(OaKeyworkTask::getId, Function.identity()));
                for (OaKeyworkWeeklyActualDTO dtoPlan : dtoList) {
                    if (dtoPlan.getType() == 2) {
                        dtoPlan.setTaskName(map.get(dtoPlan.getTaskId()) != null ? map.get(dtoPlan.getTaskId()).getTaskName() : "");
                    }
                }
            }
        }

        return dtoList;
    }
}

